package com.jastar.android.jigsaw.util;

import android.content.Context;
import android.media.MediaPlayer;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class AudioPlayer {

    private static final AudioPlayer player = new AudioPlayer();
    private static final int MAX_PLAY = 6;

    private final Executor executor = Executors.newFixedThreadPool(3);
    private final Map<Integer, MediaPlayer> playerMap = new ConcurrentHashMap<>();
    private final AtomicLong audioTag = new AtomicLong(0L);

    private AudioPlayer() {
    }

    public static AudioPlayer getPlayer() {
        return player;
    }

    public void stop() {
        audioTag.set(System.currentTimeMillis());
    }

    public void playOnce(Context context, int audioId) {
        if (!playerMap.containsKey(audioId)) {
            synchronized (this) {
                if (!playerMap.containsKey(audioId)) {
                    MediaPlayer mediaPlayer = MediaPlayer.create(context, audioId);
                    playerMap.put(audioId, mediaPlayer);
                }
            }
        }
        Objects.requireNonNull(playerMap.get(audioId)).start();
    }

    public void play(Context context, int audioId) {
        executor.execute(() -> {
            int times = 0;
            long currentAudio = System.currentTimeMillis();
            audioTag.set(currentAudio);
            Utils.sleep(1000);
            do {
                playOnce(context, audioId);
                Utils.sleep(3000);
            } while (Objects.equals(audioTag.get(), currentAudio) && (++times) < MAX_PLAY);
        });
    }

}
